package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.FocusUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Description：test
 * @Create by： 张会豪
 * @Date：2021/11/3 12:49
 */
@DubboService
public class FocusUserApiImpl implements FocusUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //视频关注
    public void save(FocusUser focusUser) {
        //1、完善对象属性值
        focusUser.setId(ObjectId.get());
        focusUser.setCreated(System.currentTimeMillis());
        //2、调用mongoTemplate保存
        mongoTemplate.save(focusUser);
    }

    //视频关注--取消
    public void delete(Long userId, Long followUserId) {
        //1、查询对应的数据
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId));
        //2、删除数据
        mongoTemplate.remove(query, FocusUser.class);
    }

    //查看当前用户是否已关注该视频用户
    public Boolean hasFocus(Long userId, Long followUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId)
        );
        return mongoTemplate.exists(query, FocusUser.class);
    }

    @Override
    public Long countFans(Long userId) {
        Query query = Query.query(Criteria.where("followUserId").is(userId));
        long count = mongoTemplate.count(query, FocusUser.class);
        return count;
    }

    @Override
    public List<FocusUser> findByUserId(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("followUserId").is(userId))
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,FocusUser.class);
    }

    @Override
    public void deleteById(Long uid,Long followUserId) {
        Query query = Query.query(Criteria.where("userId").is(uid).and("followUserId").is(followUserId));
        mongoTemplate.remove(query,FocusUser.class);
    }
}
